﻿using System;
using System.Diagnostics;
using System.Reflection;
using Hallenberg.SmartClient.Interfaces;
using Hallenberg.SmartClient.Menu;
using System.Globalization;

namespace Hallenberg.SmartClient.TypeHandlers
{
    class MenuItemAttributeHandler : BaseAttributeTypeHandler<MenuItemAttribute>
    {
        private MenuManager m_MenuManagers;
        private IResourceMapper m_ResourceMapper;
        //private ILocalization m_Localization;

        public MenuItemAttributeHandler(MenuManager menuManager, IResourceMapper resourceMapper)
        {
            m_MenuManagers = menuManager;
            m_ResourceMapper = resourceMapper;
            //m_Localization = localization;
        }

        public override bool Handle(Type attachedToClass, MethodBase attachedToMethod, MenuItemAttribute typedAttribute, Attribute[] allAttributes)
        {
            MenuItemContainer menuManager = m_MenuManagers.Find(typedAttribute.MenuCollectionName, true);

            Debug.Assert(menuManager != null);
            if (menuManager == null)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "MenuManager '{0}' could not be found", typedAttribute.MenuCollectionName));
            }

            MenuItem menuItem = new MenuItem(
                typedAttribute.MenuItemName,
                typedAttribute.MenuTitle,
                typedAttribute.ToolTip,
                typedAttribute.DisabledPolicy)
            {
                ResourceMapper = m_ResourceMapper,
                SortIndex = typedAttribute.SortIndex,
                CanExecuteEvaluator = typedAttribute.DisplayMenuEvaluator,
                AttachedToClass = attachedToClass.Name,
                AttachedToMethod = attachedToMethod.Name
            };

            //menuItem.SetCurrentLanguageIdCallback(m_Localization.GetCurrentLanguageId);
            menuManager.AddMenuItem(menuItem);

            return true;
        }
    }
}
